module DrunkenMaster  
  module Util
    class Path

      PATH_SEPARATOR = "/"

      def self.relative(from, to)
        from  = _cleanup_array(split(from))
        to    = _cleanup_array(split(to))
        join(_relative_array(from, to))
      end

      def self.cleanup path    
        join(_cleanup_array(split(path)))
      end

      def self.split path
        path.split(PATH_SEPARATOR)
      end

      def self.join path
        if path.length == 0
          "."
        else
          path.join(PATH_SEPARATOR)
        end    
      end

      private

      def self._relative_array from, to
        result = []
        same_path = true
        [from.length, to.length].max.times { |i|
          if same_path
            if from[i] != to[i]
              same_path = false
            else
              next
            end
          end
          if to[i].nil?
            result << '..'
          else
            result << to[i]
          end
        }
        result
      end  

      def self._cleanup_array path
        result = []
        #puts "\n"+path.inspect
        path.each_with_index { |node, i|
          #puts result.inspect
          next if ["", "."].include? node
          if node == ".." && result.last != '..' && !result.last.nil?
            result.pop
            next
          end
          result << node
        }
        result
      end

    end
  end
end